/**
 * Created by json on 2019/7/11.
 */
import CryptoJS from 'crypto-js';
import JSEncrypt from 'jsencrypt';

/**
 * 清除所有不可见字符
 * @param str
 */
const trim = str => {
  return str.replace(/\s+/g, '');
};

const lrtrim = str => {
  return str.replace(/(^\s+)|(\s+$)/g, '');
};

/**
 * md5编码
 * @param str {string}
 * @returns {string}
 */
const md5Encode = str => {
  return CryptoJS.MD5(str).toString();
};

/**
 * base64编码
 * @param str {string}
 * @returns {string}
 */
const base64Encode = str => {
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str));
};

/**
 * base64解码
 * @param str {string}
 * @returns {string}
 */
const base64Decode = str => {
  return CryptoJS.enc.Base64.parse(str.replace(/\s/g, '+')).toString(
    CryptoJS.enc.Utf8
  );
};

/**
 * des加密
 * @param str {string}
 * @param key {string}
 * @returns {string}
 */
const desEncrypt = (str, key) => {
  return CryptoJS.DES.encrypt(str, CryptoJS.enc.Utf8.parse(key), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString();
};

/**
 * des解密
 * @param str {string} 密文
 * @param key {string} 秘钥
 * @returns {string}
 */
const desDecrypt = (str, key) => {
  return CryptoJS.DES.decrypt(
    {
      ciphertext: CryptoJS.enc.Base64.parse(str.replace(/\s/g, ''))
    },
    CryptoJS.enc.Utf8.parse(key),
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }
  ).toString(CryptoJS.enc.Utf8);
};

/**
 * Rsa加密
 * @param str {string}
 * @returns {CipherParams|PromiseLike<ArrayBuffer>|*}
 */
const rsaEncrypt = str => {
  const RSAKEY =
    '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7vSW4bQmo05puNJ8TBYwrhfaLFBMu4lKQfYzd4LorE+VXTpRccMdInhRIMSydAY2/Csjr11mbo7F3OMK33B2PJet7nZuMCjOTiiBrQMC1h3tcT0XbFij7APJHEVlgstCmzQQ53TDNMcj9pgh/LYx7IXNRnUdl5LKDVJjlnL5AwwIDAQAB-----END PUBLIC KEY-----';
  let pubKey = RSAKEY;
  let encryptor = new JSEncrypt();
  encryptor.setPublicKey(pubKey);
  return encryptor.encrypt(str);
};

const encryptPass = password => {
  let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let keyArr = [
    32, 4, 33, 4, 26, 0, 4, 32, 35, 3, 5, 27, 30, 4, 0, 35, 26, 32, 26, 0, 34,
    4, 35, 26, 30, 26, 3, 33, 0, 5, 3, 1
  ];
  let keyStr = '',
    i = 0,
    l = 0;
  for (i = 0, l = keyArr.length; i < l; i++) {
    keyStr += str.substr(keyArr[i], 1);
  }
  return md5Encode(desEncrypt(password, keyStr));
};

export default {
  md5: md5Encode,
  base64Decode,
  base64Encode,
  encryptPass,
  desDecrypt,
  desEncrypt,
  rsaEncrypt,
  trim,
  lrtrim
};
